const { Controller } = require("egg");
const COS = require("cos-nodejs-sdk-v5");
const fs = require("fs");
const path = require("path");
class UploadCOntroller extends Controller {
  async upload() {
    const { ctx, app } = this;
    const { SecretId, SecretKey, Bucket, Region, prefix } = app.config.cos;
    if (ctx.request.files?.length) {
      console.log(ctx.request.files);
      const file = ctx.request.files[0];
      //   cos初始化
      const cos = new COS({
        SecretId,
        SecretKey,
      });
      const Key = prefix + new Date().getTime() + file.filename.slice(1);
      const res = await cos.putObject({
        Bucket,
        Region,
        Key,
        StorageClass: "STANDARD",
        Body: fs.readFileSync(file.filepath),
        Headers: { "Content-Disposition": "inline", "Content-Type": file.mime },
      });
      if (res.statusCode === 200) {
        ctx.send({ data: { url: `https://${res.Location}` } });
      } else {
        ctx.send({ error: "上传失败", success: false, code: res.statusCode });
      }
    } else {
      ctx.send({ error: "上传图片不能为空", success: false, code: 400 });
    }
  }
  async stream_download() {
    const { ctx } = this;
    const content = fs.createReadStream("public/11.jpg");
    // application/actet-stream：二进制流文件
    ctx.headers["content-type"] = "application/octet-stream";
    // Content-Disposition控制文件在浏览器下载还是预览，默认为inline预览
    ctx.headers["content-disposition"] = `attachment; filename=11.jpg`
    
    ctx.body = content
  }
}


module.exports = UploadCOntroller;
